/*
 *所有关于daojiaoGD类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*daojiaoGDService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.DbSqlSugar;
using DGZImp.Core.Exceptions;
using Newtonsoft.Json.Linq;
using static ATkg.BizAppProject.Services.material_plan_xieService;
using System.Globalization;
using DGZImp.Core.EFDbContext;
using MySql.Data.MySqlClient;
using System.Reflection.Metadata.Ecma335;
using static Org.BouncyCastle.Math.EC.ECCurve;
using System.Data;
using Dapper;
using MySql.Data.MySqlClient;
using System.Collections.Generic;
using System.Data;
using DbType = SqlSugar.DbType;
using DocumentFormat.OpenXml.Math;
using System.Runtime.InteropServices;
using SqlSugar;
using DocumentFormat.OpenXml.Office2010.Word;
using static ATkg.BizAppProject.Services.daojiaoGDService;
using DocumentFormat.OpenXml.Wordprocessing;
using TDengine.Driver;
using TDengine.Driver.Client;
using System.Text.Json;
using System.Text;
using TDengine; // 假设使用TDengine原生驱动
using System.Collections.Generic;
using DocumentFormat.OpenXml;
using System.DirectoryServices.ActiveDirectory;
using DocumentFormat.OpenXml.Drawing;



namespace ATkg.BizAppProject.Services
{
    public partial class daojiaoGDService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IdaojiaoGDRepository _repository;//访问数据库
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        //public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        public AmesSyncService ames = AutofacContainerModule.GetService<AmesSyncService>();

        [ActivatorUtilitiesConstructor]
        public daojiaoGDService(
            IdaojiaoGDRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        [SugarTable("daojiaogd")] // 映射表名
        public class Daojiaogd
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string schedule_id { get; set; }
            public string name { get; set; }
            public string raw_lot_id { get; set; }
            public string grade { get; set; }
            public string plating { get; set; }
            public string lot_ids { get; set; }
            public string prodcut_spec { get; set; }
            public decimal raw_resume_weight { get; set; }
            public decimal product_qty { get; set; }
            public string product_id { get; set; }
            public string state { get; set; }
            public string quality_judge { get; set; }
        }
        public class Devices
        {
            public string Name { get; set; }
            public string CategoryId { get; set; }
            public int SerialNo { get; set; }
            public string CcdStatus { get; set; }
            public int Mesid { get; set; }
            public int XianTi { get; set; }
            public string DianJian { get; set; }
            public string Numb { get; set; }

        }
        public async Task<object> get_info_from_bfmes()
        {
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Console.WriteLine(formattedTime); // 输出示例：2025-06-17 14:30:45
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            //ames.url = "http://10.16.12.81/jsonrpc";
            ames.url = "http://10.16.12.80/jsonrpc";
            ames.db = "bt";
            // 1. 构建domain条件树
            var domain1 = new List<object>
            {
                "|",
                "|",
                "|",
                new List<object> { "name", "ilike", "倒角机" },
                new List<object> { "model", "ilike", "倒角机" },
                new List<object> { "serial_no", "ilike", "倒角机" },
                new List<object> { "partner_ref", "ilike", "倒角机" },
            };
            // 2. 构建specification字段映射
            var specification = new Dictionary<string, object>
            {
                {
                    "category_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },                
                { "state", new Dictionary<string, object>() },
                { "nick_name", new Dictionary<string, object>() },
                { "serial_no", new Dictionary<string, object>() },
                { "ccd_status", new Dictionary<string, object>() },
                { "class_type", new Dictionary<string, object>() }
            };
            // 3. 组合最终结构category_id
            var result = new Dictionary<string, object>
            {
                { "domain", domain1 },
                { "specification", specification }
            };
            var resp = await ames.Get_web_search_read("maintenance.equipment", result);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"]["records"];
            var final_data_info_ = new List<Devices>();
            for(int i = 0; i < record.Count; i++)
            {
                Console.WriteLine(record[i]);
                int xianti_numb = 0;
                var nick_name_ = (string)record[i]["nick_name"];
                string[] result_name = nick_name_.Split("#");
                if (result_name[1] != "倒角机上下料")
                {
                    if (int.Parse(result_name[0]) <= 5)
                    {
                        xianti_numb = 1;
                        //record[i].Ad
                    }
                    else if(int.Parse(result_name[0]) > 10)
                    {
                        xianti_numb = 2;
                    }
                }
                else
                {
                    xianti_numb = 0;
                }
                
                final_data_info_.Add(new Devices
                {
                    Name = (string)record[i]["nick_name"],
                    SerialNo = (int)record[i]["serial_no"],
                    CategoryId = (string)record[i]["category_id"]["display_name"],
                    Mesid = (int)record[i]["id"],
                    CcdStatus = record[i]["ccd_status"].Type == JTokenType.Boolean ? null : (string)record[i]["ccd_status"],
                    XianTi = xianti_numb,
                });
            }

            BulkInsertWithDapper(final_data_info_); // 方法二
            return final_data_info_;
        }
        public static void BulkInsertWithDapper(List<Devices> data)
        {
            string connStr = "Server=10.16.12.72;Port=3306;Database=biz_app;Uid=root;Pwd=fastbee;";
            for(int i = 0; i < data.Count; i++){
                long count = GetCountByname(data[i].Name,connStr);
                if (count > 0)
                {
                    continue;
                }
                else
                {
                    using (var conn = new MySqlConnection(connStr))
                    {
                        string sql = "INSERT INTO daojiao_shebei (name, current_order, category_id, serial_no, ccd_status,xianti_numb, mesid) " +
                                    "VALUES (@Name, '', @CategoryId, @SerialNo, @CcdStatus,@XianTi, @Mesid)";
                        conn.Execute(sql, data[i]); // 自动映射对象属性到参数
                    }
                }
            }
        }
        public static long GetCountByname(string name,string connStr)
        {
            string query = @"SELECT COUNT(*) AS count FROM daojiao_shebei WHERE name = @name";
            using (var conn = new MySqlConnection(connStr))
            {
                // 自动映射结果到匿名对象
                var result = conn.QueryFirstOrDefault(query, new { name });
                return result.count;
            }
        }

        [SugarTable("daojiao_shebei")]
        public partial class daojiao_shebei_dj
        {
            [SugarColumn(IsPrimaryKey = true)]
            public int id { get; set; }
            public string name { get; set; }
            public string category_id { get; set; }
            public int serial_no { get; set; }
            public string ccd_status { get; set; }
            public int mesid { get; set; }
            public int xianti_numb { get; set; }
            public string dj { get; set; }
            public string number { get; set; }
        }

        public async Task<object> get_dj_from_bfmes()
        {
            DateTime currentDate = DateTime.Today;

            // 获取前一天日期
            DateTime previousDate = currentDate.AddDays(-1);
            string currentDateStr1 = currentDate.ToString("yyyy-MM-dd") +" 16:00:00";
            string previousDateStr1 = previousDate.ToString("yyyy-MM-dd") + " 16:00:00";

            string connectionString = "Server=10.16.12.72;Port=3306;Database=biz_app;Uid=root;Pwd=fastbee;";
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = connectionString,
                IsAutoCloseConnection = false//设成关闭这个代码会直接报错
            });
            IAdo ado = db.Ado;
            // 执行查询并返回 DataTable
            var row = ado.GetDataTable("SELECT * FROM `daojiao_shebei`");
            var final_data_info_ = new List<Devices>();
            for (int i = 0; i < row.Rows.Count; i++)
            {
                ames.userName = "duyang@atmcn.com";
                ames.password = "Antai@2025";
                ames.url = "http://10.16.12.80/jsonrpc";
                //ames.url = "http://10.16.12.81/jsonrpc";
                ames.db = "bt";
                // 1. 构建domain条件树
                var domain1 = new List<object>
                {
                    "&",
                    new List<object> { "equipment_id.nick_name", "ilike", row.Rows[i]["name"] },
                    "&",
                    new List<object> { "date", ">=", previousDateStr1},
                    new List<object> { "date", "<=", currentDateStr1 },
                };
                // 2. 构建specification字段映射
                var specification = new Dictionary<string, object>
                {
                    { "name", new Dictionary<string, object>() }
                };
                // 3. 组合最终结构category_id
                var result = new Dictionary<string, object>
                {
                    { "domain", domain1 },
                    { "specification", specification }
                };
                var resp = await ames.Get_web_search_read("maintenance.check", result);
                if (resp.ContainsKey("error"))
                {
                    var message = $"【拉取单据】{resp["error"].ToString()}";
                    throw new AppException(message);
                }
                var record = (JArray)resp["result"]["records"];
                Console.WriteLine(resp);
                string dj_detail = "";
                if ((int)resp["result"]["length"] > 0)
                {
                    dj_detail = "已点检";
                }
                else
                {
                    dj_detail = "";
                }
                int rowsAffected = Db.Updateable<daojiao_shebei_dj>()
                    .SetColumns(it => new daojiao_shebei_dj()
                    {
                        dj = dj_detail,
                    })
                    .Where(it => it.name == row.Rows[i]["name"]) // 精确条件
                    .ExecuteCommand();

                //Db.

            }

            var Data = Db.Queryable<daojiao_shebei_dj>()
                .ToList();

            return Data;
        }
        public async Task<object> get_order_from_bfmes()
        {
            Dictionary<string, string> statusDict = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "confirmed", "等待原材料" },
                    { "progress", "进行中" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                    { "produced", "产出" },
                    { "qc_pass", "质检完成" },
                    { "rework", "返工" },
                    { "done", "完成" },
                    { "to_close", "待关闭" },
                    { "cancel", "已取消" },
                };
            Dictionary<string, string> quality_state = new Dictionary<string, string>
                {
                    { "none", "待判定" },
                    { "major_pass", "通过主要检测" },
                    { "pass", "通过" },
                    { "givein", "通过1" },
                    { "recheck", "返检" },
                    { "rework", "返工" },
                    { "scrap", "报废" },
                    { "recycle", "再利用" },
                    { "downshift", "降档使用" }
                };
            DateTime now = DateTime.Now;
            string formattedTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            // 安全转换（不抛异常）
            if (DateTime.TryParseExact(
                formattedTime,
                "yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture, // 忽略区域差异
                DateTimeStyles.None,
                out DateTime result_date))
            {
                Console.WriteLine($"转换成功: {result_date}");
            }
            else
            {
                Console.WriteLine("格式错误！");
            }
            Console.WriteLine(formattedTime); // 输出示例：2025-06-17 14:30:45
            //await Db.DoDeleteAsync<material_plan_xie>(x => x.CreateId >= 0, true);
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            //ames.url = "http://10.16.12.81/jsonrpc";
            ames.url = "http://10.16.12.80/jsonrpc";
            ames.db = "bt";
            //var isSingle = taskNo.IsValuable();
            //Console.WriteLine(taskNo);
            //var typeArray = new[] { "final" };

            // 1. 构建domain条件树
            var domain1 = new List<object>
            {
                "&",
                new List<object> { "production_type", "=", "white" },
                "&",
                new List<object> { "current_procedure_id", "in", new List<int>{10 } },
                new List<object> { "state", "not in", new List<string>{ "cancel", "to_close" } }
            };

            // 2. 构建specification字段映射
            var specification = new Dictionary<string, object>
            {
                {
                    "schedule_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "name", new Dictionary<string, object>() },
                {
                    "raw_lot_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "grade", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "plating", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "lot_ids", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "prodcut_spec", new Dictionary<string, object>() },
                { "raw_resume_weight", new Dictionary<string, object>() },
                { "product_qty", new Dictionary<string, object>() },
                {
                    "product_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "state", new Dictionary<string, object>() },
                { "quality_judge", new Dictionary<string, object>() },
            };

            // 3. 组合最终结构
            var result = new Dictionary<string, object>
            {
                { "domain", domain1 },
                { "specification", specification }
            };

            var resp = await ames.Get_web_search_read("mrp.production", result);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"]["records"];

            for(int i = 0; i < record.Count; i++)
            {
                Console.WriteLine(record[i]);
                var final_data_info = new List<daojiaoGD>();

                Console.WriteLine(record[i]["raw_lot_id"]);
                Console.WriteLine(record[i]["raw_lot_id"].GetType());
                final_data_info.Add(new daojiaoGD
                {
                    schedule_id = record[i]["schedule_id"].Type == JTokenType.Boolean ? null : (string)record[i]["schedule_id"]["display_name"],
                    name = record[i]["name"].Type == JTokenType.Boolean ? null : (string)record[i]["name"],  // 更新字段1
                    raw_lot_id = record[i]["raw_lot_id"].Type == JTokenType.Boolean ? null: (string)record[i]["raw_lot_id"]["display_name"],           // 更新字段2
                    grade = record[i]["grade"].Type == JTokenType.Boolean ? null : (string)record[i]["grade"]["display_name"],  // 更新字段1
                    plating = record[i]["plating"].Type == JTokenType.Boolean ? null : (string)record[i]["plating"]["display_name"],           // 更新字段2
                    lot_ids = ((JArray)record[i]["lot_ids"]).Count > 0 ? (string)record[i]["lot_ids"][0]["display_name"]:null,  // 更新字段1
                    prodcut_spec = record[i]["prodcut_spec"].Type == JTokenType.Boolean ? null : (string)record[i]["prodcut_spec"],           // 更新字段2
                    raw_resume_weight = record[i]["raw_resume_weight"].Type == JTokenType.Boolean ? null : (decimal)record[i]["raw_resume_weight"],  // 更新字段1
                    product_qty = record[i]["product_qty"].Type == JTokenType.Boolean ? null : (decimal)record[i]["product_qty"],           // 更新字段2
                    product_id = record[i]["product_id"].Type == JTokenType.Boolean ? null : (string)record[i]["product_id"]["display_name"],  // 更新字段1
                    state = record[i]["state"].Type == JTokenType.Boolean ? null : statusDict[(string)record[i]["state"]],  // 更新字段1
                    quality_judge = record[i]["quality_judge"].Type == JTokenType.Boolean ? null : quality_state[(string)record[i]["quality_judge"]],  // 更新字段1
                });
                var find_data = Db.Queryable<daojiaoGD>()
                    .Where(mp => mp.name == (string)record[i]["name"])
                    .ToList();
                var re = find_data.Count;

                if (re > 0)
                {
                    int rowsAffected = Db.Updateable<Daojiaogd>()
                    .SetColumns(it => new Daojiaogd()
                    {
                        schedule_id = record[i]["schedule_id"].Type == JTokenType.Boolean ? null : (string)record[i]["schedule_id"]["display_name"],  // 更新字段1
                        raw_lot_id = record[i]["raw_lot_id"].Type == JTokenType.Boolean ? null : (string)record[i]["raw_lot_id"]["display_name"],           // 更新字段2
                        grade = record[i]["grade"].Type == JTokenType.Boolean ? null : (string)record[i]["grade"]["display_name"],  // 更新字段1
                        plating = record[i]["plating"].Type == JTokenType.Boolean ? null : (string)record[i]["plating"]["display_name"],           // 更新字段2
                        lot_ids = record[i]["lot_ids"].Type == JTokenType.Boolean ? null : (string)record[i]["lot_ids"][0]["display_name"],  // 更新字段1
                        prodcut_spec = record[i]["prodcut_spec"].Type == JTokenType.Boolean ? null : (string)record[i]["prodcut_spec"],           // 更新字段2
                        raw_resume_weight = (decimal)record[i]["raw_resume_weight"],  // 更新字段1
                        product_qty = (decimal)record[i]["product_qty"],           // 更新字段2
                        product_id = record[i]["product_id"].Type == JTokenType.Boolean ? null : (string)record[i]["product_id"]["display_name"],  // 更新字段1
                        state = record[i]["state"].Type == JTokenType.Boolean ? null : statusDict[(string)record[i]["state"]],  // 更新字段1
                        quality_judge = record[i]["quality_judge"].Type == JTokenType.Boolean ? null : quality_state[(string)record[i]["quality_judge"]],  // 更新字段1

                    })
                    .Where(it => it.name == (string)record[i]["name"]) // 精确条件
                    .ExecuteCommand();
                }
                else
                {                    
                    await Db.DoInsertAsync<daojiaoGD>(final_data_info);
                }
            }           

            return resp["result"];
        }
        public async Task<object> get_devices_db()
        {
            Dictionary<string, string> statusDict = new Dictionary<string, string>
                {
                    { "run", "运行" },
                    { "fault", "故障" },
                    { "waiting", "待机" },
                    { "no", "未排产" },
                    { "other", "其他" }
                };
            // 数据库连接字符串（根据实际情况修改）
            //var ccdstatus = { "run":"运行","fault":"故障","waiting":"待机","no":"未排产","other":"其他"}
            string connectionString = "Server=10.16.12.72;Port=3306;Database=biz_app;Uid=root;Pwd=fastbee;";
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = connectionString,
                IsAutoCloseConnection = false//设成关闭这个代码会直接报错
            });
            IAdo ado = db.Ado;
            // 执行查询并返回 DataTable
            var row = ado.GetDataTable("SELECT * FROM `daojiao_shebei` WHERE current_order = ''");
            for(int i = 0; i < row.Rows.Count; i++)
            {
                row.Rows[i]["ccd_status"] = Convert.ToString(row.Rows[i]["ccd_status"]) == "" ? "": statusDict[(string)row.Rows[i]["ccd_status"]];
            }
                Console.WriteLine(row.GetType);
            //Array a = (Array)row;

            return new
            {
                rows = row,
                total = 1
            };
        }

        public async Task<object> get_devices_db_taizhang()
        {
            Dictionary<string, string> statusDict = new Dictionary<string, string>
                {
                    { "run", "运行" },
                    { "fault", "故障" },
                    { "waiting", "待机" },
                    { "no", "未排产" },
                    { "other", "其他" }
                };
            // 数据库连接字符串（根据实际情况修改）
            //var ccdstatus = { "run":"运行","fault":"故障","waiting":"待机","no":"未排产","other":"其他"}
            string connectionString = "Server=10.16.12.72;Port=3306;Database=biz_app;Uid=root;Pwd=fastbee;";
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = connectionString,
                IsAutoCloseConnection = false//设成关闭这个代码会直接报错
            });
            IAdo ado = db.Ado;
            // 执行查询并返回 DataTable
            var row = ado.GetDataTable("SELECT * FROM `daojiao_shebei`");
            for (int i = 0; i < row.Rows.Count; i++)
            {
                row.Rows[i]["ccd_status"] = Convert.ToString(row.Rows[i]["ccd_status"]) == "" ? "" : statusDict[(string)row.Rows[i]["ccd_status"]];
            }
            Console.WriteLine(row.GetType);
            //Array a = (Array)row;
            return new
            {
                rows = row,
                total = 1
            };
        }

        public async Task<string> dianjian_daojiao_devices(string shebei_type, int mesid)
        {
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            //ames.url = "http://10.16.12.81/jsonrpc";
            ames.url = "http://10.16.12.80/jsonrpc";
            ames.db = "bt";
            // 1. 构建domain条件树
            
            // 2. 构建specification字段映射

            // 3. 组合最终结构category_id
            int category_id_ = 248;
            if (shebei_type != "倒角机XXZP-C300")
            {
                category_id_ = 249;
            }
            var para_ = new Dictionary<string, object>
                {
                    { "category_ids", new List<object>{ new List<object> { 4, category_id_ } } },
                    { "equipment_ids", new List<object>{ new List<object> { 4, mesid } }  }
                };
            var domain1 = new List<object>
                {
                    new List<object> { },
                    para_
                };
            var resp = await ames.web_save("wizard.batch.check", domain1);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"];
            Console.WriteLine(resp);
            Console.WriteLine(record[0]["id"]);
            int dianjian_id = int.Parse((string)record[0]["id"]);
            try
            {
                // hanshu: 替换为实际的XML-RPC方法调用
                // 例如: client.Call("MethodName", parameters);
                var confirm = new List<object>
                {
                    new List<object> { dianjian_id }
                };
                var resp_confirm = await ames.btn_confirm("wizard.batch.check", confirm, "btn_confirm");
                Console.WriteLine(resp_confirm);
                string dj_detail = "";
                if (resp_confirm == "成功")
                {
                    dj_detail = "已点检";
                    int rowsAffected = Db.Updateable<daojiao_shebei_dj>()
                        .SetColumns(it => new daojiao_shebei_dj()
                        {
                            dj = dj_detail,
                        })
                        .Where(it => it.mesid == mesid) // 精确条件
                        .ExecuteCommand();
                }
                return resp_confirm;
            }
            catch(Exception ex)
            {
                if (ex.Message.Contains("cannot marshal None"))
                {
                    Console.WriteLine("操作成功完成（服务端返回了None）");
                    // 执行后续操作
                }
                else
                {
                    // 重新抛出原始异常以保持堆栈跟踪
                    Console.WriteLine("这里的吗？？");
                    
                }
                return "失败";
            }           
        }

        public async Task<object> get_wb_from_bfmes()
        {

            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            ames.url = "http://10.16.12.80/jsonrpc";
            //ames.url = "http://10.16.12.81/jsonrpc";
            ames.db = "bt";
            // 1. 构建domain条件树
            var domain1 = new List<object>
                {
                    "&",
                    new List<object> { "archive", "=", false},
                    "&",
                    new List<object> { "equipment_id.nick_name", "ilike","倒角机" },
                    new List<object> { "stage_id", "not ilike", "已维修" },
                };
            // 2. 构建specification字段映射
            var specification = new Dictionary<string, object>
            {
                { "name", new Dictionary<string, object>() },
                {
                    "equipment_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "work_order_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "request_date", new Dictionary<string, object>() },
                { "schedule_date", new Dictionary<string, object>() },
                {
                    "employee_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "user_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "category_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "stage_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
            };
            // 3. 组合最终结构category_id
            var result = new Dictionary<string, object>
                {
                    { "domain", domain1 },
                    { "specification", specification }
                };
            var resp = await ames.Get_web_search_read("maintenance.request", result);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"]["records"];
            Console.WriteLine(resp);

            //var Data = Db.Queryable<daojiao_shebei_dj>()
            //    .ToList();

            return record;
        }

        public async Task<string> wb_daojiao_devices(string shebei_type, int mesid, string wb_name)
        {
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            //ames.url = "http://10.16.12.81/jsonrpc";
            ames.url = "http://10.16.12.80/jsonrpc";
            ames.db = "bt";
            var para_ = new Dictionary<string, object>
                {
                    { "name", wb_name },
                    { "equipment_id", mesid  },
                    { "user_id", 434  }
                };
            var domain1 = new List<object>
                {
                    new List<object> { },
                    para_
                };
            var resp = await ames.web_save("maintenance.request", domain1);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"];
            Console.WriteLine(resp);
            Console.WriteLine(record[0]["id"]);
            
            try
            {
                int wb_id = int.Parse((string)record[0]["id"]);                
                return "成功";
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("cannot marshal None"))
                {
                    Console.WriteLine("操作成功完成（服务端返回了None）");
                    // 执行后续操作
                }
                else
                {
                    // 重新抛出原始异常以保持堆栈跟踪
                    Console.WriteLine("这里的吗？？");

                }
                //object Data = new object();

                return "失败";
            }
        }


        public async Task<string> wb_daojiao_done_devices(string option_type, JArray done_type, int mesid, string wb_name)
        {
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            ames.url = "http://10.16.12.80/jsonrpc";
            //ames.url = "http://10.16.12.81/jsonrpc";
            ames.db = "bt";
            var modles = "";
            Console.WriteLine(done_type);
            var domain1 = new List<object>();
            domain1.Add(new List<object> { });
            if (option_type == "验收")
            {
                modles = "maintenance.request.check.wizard";
                if ((string)done_type[0]["acceptanceResult"] == "合格")
                {
                    domain1.Add(
                        new Dictionary<string, object>
                        {
                            {"check_state","qualified" },
                            {"request_id",mesid },
                            {"unqualified_reason",false }
                        }
                    );
                }
            }
            else
            {
                modles = "maintenance.request.evaluation.wizard";
                if ((string)done_type[0]["evaluation"]["rating"] == "满意")
                {
                    domain1.Add(
                        new Dictionary<string, object>
                        {
                            {"evaluation_note","满意" },
                            {"evaluation_state","satisfy" },
                            {"request_id",mesid }
                        }
                    );
                }
            }
            Console.WriteLine(domain1);
            Console.WriteLine(modles);
            var resp = await ames.web_save(modles, domain1);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"];
            Console.WriteLine(resp);
            Console.WriteLine(record[0]["id"]);

            try
            {
                int wb_id = int.Parse((string)record[0]["id"]);
                var confirm = new List<object>
                {
                    new List<object> { wb_id }
                };
                var resp_confirm = await ames.btn_confirm(modles, confirm, "button_done");
                if(resp_confirm == "成功")
                {
                    return "成功";
                }
                else
                {
                    return "失败";
                }
                
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("cannot marshal None"))
                {
                    Console.WriteLine("操作成功完成（服务端返回了None）");
                    // 执行后续操作
                }
                else
                {
                    // 重新抛出原始异常以保持堆栈跟踪
                    Console.WriteLine("这里的吗？？");

                }
                //object Data = new object();

                return "失败";
            }
        }

        [SugarTable("dj_dg_qulity")] // 映射表名
        public class dj_dg_qulity
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string point_id { get; set; }
            public string product_id { get; set; }
            public string lot_id { get; set; }
            public string inspect_type_id { get; set; }
            public string inspect_id { get; set; }
            public string judgement { get; set; }
            public string control_date { get; set; }
            public string user_id { get; set; }
            public string qulity_state { get; set; }
        }
        public async Task<object> order_qulity_mes()
        {
            var find_data_gd = Db.Queryable<Daojiaogd>()
                    .ToList();
            Console.WriteLine(find_data_gd.Count);
            Dictionary<string, string> quality_state = new Dictionary<string, string>
                {
                    { "none", "待处理" },
                    { "pending", "待处置" },
                    { "pass", "通过" },
                    {"inside_pass","通过2" },
                    { "givein", "通过1" },
                    { "rework", "返工" },
                    { "scrap", "报废" },
                    { "recycle", "再利用" },
                    { "partial_fai1", "部分失败" },
                    { "none_partial_fai1", "部分失败" },
                    { "downshift", "降档使用" },
                    { "fai1", "部分失败" }
                };
            ames.userName = "duyang@atmcn.com";
            ames.password = "Antai@2025";
            ames.url = "http://10.16.12.80/jsonrpc";
            //ames.url = "http://10.16.12.81/jsonrpc";
            ames.db = "bt";
            // 2. 构建specification字段映射
            var specification = new Dictionary<string, object>
            {
                {
                    "point_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "product_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "lot_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "inspect_type_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                {
                    "inspect_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "judgement", new Dictionary<string, object>() },
                { "control_date", new Dictionary<string, object>() },
                {
                    "user_id", new Dictionary<string, object>
                    {
                        { "fields", new Dictionary<string, object> { { "display_name", new Dictionary<string, object>() } } }
                    }
                },
                { "quality_state", new Dictionary<string, object>() },
            };
            for (int per = 0; per < find_data_gd.Count; per++)
            {
                // 1. 构建domain条件树
                string lot_id_name = find_data_gd[per].name;
                var domain1 = new List<object>
                {
                    new List<object> { "lot_id", "ilike", lot_id_name },
                };
                // 3. 组合最终结构category_id
                var result = new Dictionary<string, object>
                {
                    { "domain", domain1 },
                    { "specification", specification }
                };
                var resp = await ames.Get_web_search_read("quality.check", result);
                if (resp.ContainsKey("error"))
                {
                    var message = $"【拉取单据】{resp["error"].ToString()}";
                    throw new AppException(message);
                }
                var record = (JArray)resp["result"]["records"];

                for (int i = 0; i < record.Count; i++)
                {
                    Console.WriteLine(record[i]);
                    var final_data_info = new List<dj_dg_qulity>();

                    final_data_info.Add(new dj_dg_qulity
                    {
                        point_id = record[i]["point_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["point_id"]["display_name"],
                        product_id = record[i]["product_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["product_id"]["display_name"],  // 更新字段1
                        lot_id = record[i]["lot_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["lot_id"]["display_name"],           // 更新字段2
                        inspect_type_id = record[i]["inspect_type_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["inspect_type_id"]["display_name"],  // 更新字段1
                        inspect_id = record[i]["inspect_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["inspect_id"]["display_name"],           // 更新字段2
                        judgement = record[i]["judgement"].Type == JTokenType.Boolean ? "" : (string)record[i]["judgement"],  // 更新字段1
                        control_date = record[i]["control_date"].Type == JTokenType.Boolean ? "" : (string)record[i]["control_date"],           // 更新字段2
                        user_id = record[i]["user_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["user_id"]["display_name"],  // 更新字段1
                        qulity_state = record[i]["quality_state"].Type == JTokenType.Boolean ? "" : quality_state[(string)record[i]["quality_state"]],       //字段1
                    });
                    var find_data = Db.Queryable<dj_dg_qulity>()
                        .Where(mp => mp.inspect_id == (string)record[i]["inspect_id"]["display_name"])
                        .ToList();
                    var re = find_data.Count;

                    if (re > 0)
                    {
                        string quality_ = record[i]["quality_state"].Type == JTokenType.Boolean ? "" : quality_state[(string)record[i]["quality_state"]];
                        if ((string)find_data[0].qulity_state != quality_)
                        {
                            int rowsAffected = Db.Updateable<dj_dg_qulity>()
                            .SetColumns(it => new dj_dg_qulity()
                            {
                                point_id = record[i]["point_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["point_id"]["display_name"],
                                product_id = record[i]["product_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["product_id"]["display_name"],  // 更新字段1
                                                                                                                                                         //lot_id = record[i]["lot_id"].Type == JTokenType.Boolean ? null : (string)record[i]["lot_id"]["display_name"],           // 更新字段2
                                inspect_type_id = record[i]["inspect_type_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["inspect_type_id"]["display_name"],  // 更新字段1
                                inspect_id = record[i]["inspect_id"].Type == JTokenType.Boolean ? "" : (string)record[i]["inspect_id"]["display_name"],           // 更新字段2
                                judgement = record[i]["judgement"].Type == JTokenType.Boolean ? "" : (string)record[i]["judgement"],  // 更新字段1
                                control_date = record[i]["control_date"].Type == JTokenType.Boolean ? "" : (string)record[i]["control_date"],           // 更新字段2
                                                                                                                                                        //user_id = "",  // 更新字段1
                                qulity_state = record[i]["quality_state"].Type == JTokenType.Boolean ? "" : quality_state[(string)record[i]["quality_state"]],   // 更新字段1

                            })
                            .Where(it => it.inspect_id == (string)record[i]["inspect_id"]["display_name"]) // 精确条件
                            .ExecuteCommand();
                        }
                        else
                        {
                            Console.WriteLine("L");
                        }

                    }
                    else
                    {
                        await Db.DoInsertAsync<dj_dg_qulity>(final_data_info);
                        //Console.WriteLine("LLLL");
                    }
                }
            }
            return "成功";
        }

        [SugarTable("daojiao_technology")] // 映射表名
        public class daojiao_technology
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string Name { get; set; }
            public string ProductName { get; set; }
            public string GuiGe { get; set; }
            public string XinNneng { get; set; }
            public string abrasiveWeight1 { get; set; }
            public string workpieceWeight1 { get; set; }
            public string singleBasketWeight1 { get; set; }
            public string leakagePosition1 { get; set; }
            public string leakageTime1 { get; set; }
            public string leakagePartPosition1 { get; set; }
            public string leakagePartTime1 { get; set; }
            public string flyBarPosition1 { get; set; }
            public string flyBarPosition12 { get; set; }
            public string softStartTime1 { get; set; }
            public string softStartFrequency1 { get; set; }
            public string abrasiveWeight2 { get; set; }
            public string workpieceWeight2 { get; set; }
            public string singleBasketWeight2 { get; set; }
            public string leakagePosition2 { get; set; }
            public string leakageTime2 { get; set; }
            public string leakagePartPosition2 { get; set; }
            public string leakagePartTime2 { get; set; }
            public string flyBarPosition2 { get; set; }
            public string flyBarPosition22 { get; set; }
            public string softStartTime2 { get; set; }
            public string softStartFrequency2 { get; set; }
            public string step1 { get; set; }
            public string time1 { get; set; }
            public string step2 { get; set; }
            public string time2 { get; set; }
            public string step3 { get; set; }
            public string time3 { get; set; }
            public string step4 { get; set; }
            public string time4 { get; set; }
            public string step5 { get; set; }
            public string time5 { get; set; }
            public string step6 { get; set; }
            public string time6 { get; set; }
            public string step7 { get; set; }
            public string time7 { get; set; }
            public string step8 { get; set; }
            public string time8 { get; set; }
            public string step9 { get; set; }
            public string time9 { get; set; }
            public string step10 { get; set; }
            public string time10 { get; set; }
        }

        public async Task<object> technology_db(JArray mes_data)
        {
            var db_data = mes_data[1];
            var final_data_info = new List<daojiao_technology>();
            final_data_info.Add(new daojiao_technology
            {
                Name = (string)db_data["Name"],
                ProductName = (string)db_data["ProductName"],
                GuiGe = (string)db_data["GuiGe"],
                XinNneng = (string)db_data["XinNneng"],
                abrasiveWeight1 = (string)db_data["abrasiveWeight1"],
                workpieceWeight1 = (string)db_data["workpieceWeight1"],
                singleBasketWeight1 = (string)db_data["singleBasketWeight1"],
                leakagePosition1 = (string)db_data["leakagePosition1"],
                leakageTime1 = (string)db_data["leakageTime1"],
                leakagePartPosition1 = (string)db_data["leakagePartPosition1"],
                leakagePartTime1 = (string)db_data["leakagePartTime1"],
                flyBarPosition1 = (string)db_data["flyBarPosition1"],
                flyBarPosition12 = (string)db_data["flyBarPosition12"],
                softStartTime1 = (string)db_data["softStartTime1"],
                softStartFrequency1 = (string)db_data["softStartFrequency1"],
                abrasiveWeight2 = (string)db_data["abrasiveWeight2"],
                workpieceWeight2 = (string)db_data["workpieceWeight2"],
                singleBasketWeight2 = (string)db_data["singleBasketWeight2"],
                leakagePosition2 = (string)db_data["leakagePosition2"],
                leakageTime2 = (string)db_data["leakageTime2"],
                leakagePartPosition2 = (string)db_data["leakagePartPosition2"],
                leakagePartTime2 = (string)db_data["leakagePartTime2"],
                flyBarPosition2 = (string)db_data["flyBarPosition2"],
                flyBarPosition22 = (string)db_data["flyBarPosition22"],
                softStartTime2 = (string)db_data["softStartTime2"],
                softStartFrequency2 = (string)db_data["softStartFrequency2"],
                step1 = (string)db_data["step1"],
                time1 = (string)db_data["time1"],
                step2 = (string)db_data["step2"],
                time2 = (string)db_data["time2"],
                step3 = (string)db_data["step3"],
                time3 = (string)db_data["time3"],
                step4 = (string)db_data["step4"],
                time4 = (string)db_data["time4"],
                step5 = (string)db_data["step5"],
                time5 = (string)db_data["time5"],
                step6 = (string)db_data["step6"],
                time6 = (string)db_data["time6"],
                step7 = (string)db_data["step7"],
                time7 = (string)db_data["time7"],
                step8 = (string)db_data["step8"],
                time8 = (string)db_data["time8"],
                step9 = (string)db_data["step9"],
                time9 = (string)db_data["time9"],
                step10 = (string)db_data["step10"],
                time10 = (string)db_data["time10"],
            });
            Console.WriteLine(mes_data);
            if ((string)mes_data[0] == "查询")
            {
                Console.WriteLine("查询");
                var find_data_TC = Db.Queryable<daojiao_technology>()
                    .ToList();
                Console.WriteLine(find_data_TC.Count);
                return new
                {
                    data_all = find_data_TC,
                    type = "查询成功"
                };
            }
            else if((string)mes_data[0] == "编辑")
            {
                Console.WriteLine("编辑");
                //var db_data = mes_data[1];
                var name = db_data["Name"];
                int rowsAffected = Db.Updateable<daojiao_technology>()
                    .SetColumns(it => new daojiao_technology()
                    {
                        Name = (string)db_data["Name"],
                        ProductName = (string)db_data["ProductName"],
                        GuiGe = (string)db_data["GuiGe"],
                        XinNneng = (string)db_data["XinNneng"],
                        abrasiveWeight1 = (string)db_data["abrasiveWeight1"],
                        workpieceWeight1 = (string)db_data["workpieceWeight1"],
                        singleBasketWeight1 = (string)db_data["singleBasketWeight1"],
                        leakagePosition1 = (string)db_data["leakagePosition1"],
                        leakageTime1 = (string)db_data["leakageTime1"],
                        leakagePartPosition1 = (string)db_data["leakagePartPosition1"],
                        leakagePartTime1 = (string)db_data["leakagePartTime1"],
                        flyBarPosition1 = (string)db_data["flyBarPosition1"],
                        flyBarPosition12 = (string)db_data["flyBarPosition12"],
                        softStartTime1 = (string)db_data["softStartTime1"],
                        softStartFrequency1 = (string)db_data["softStartFrequency1"],
                        abrasiveWeight2 = (string)db_data["abrasiveWeight2"],
                        workpieceWeight2 = (string)db_data["workpieceWeight2"],
                        singleBasketWeight2 = (string)db_data["singleBasketWeight2"],
                        leakagePosition2 = (string)db_data["leakagePosition2"],
                        leakageTime2 = (string)db_data["leakageTime2"],
                        leakagePartPosition2 = (string)db_data["leakagePartPosition2"],
                        leakagePartTime2 = (string)db_data["leakagePartTime2"],
                        flyBarPosition2 = (string)db_data["flyBarPosition2"],
                        flyBarPosition22 = (string)db_data["flyBarPosition22"],
                        softStartTime2 = (string)db_data["softStartTime2"],
                        softStartFrequency2 = (string)db_data["softStartFrequency2"],
                        step1 = (string)db_data["step1"],
                        time1 = (string)db_data["time1"],
                        step2 = (string)db_data["step2"],
                        time2 = (string)db_data["time2"],
                        step3 = (string)db_data["step3"],
                        time3 = (string)db_data["time3"],
                        step4 = (string)db_data["step4"],
                        time4 = (string)db_data["time4"],
                        step5 = (string)db_data["step5"],
                        time5 = (string)db_data["time5"],
                        step6 = (string)db_data["step6"],
                        time6 = (string)db_data["time6"],
                        step7 = (string)db_data["step7"],
                        time7 = (string)db_data["time7"],
                        step8 = (string)db_data["step8"],
                        time8 = (string)db_data["time8"],
                        step9 = (string)db_data["step9"],
                        time9 = (string)db_data["time9"],
                        step10 = (string)db_data["step10"],
                        time10 = (string)db_data["time10"],
                    })
                    .Where(it => it.Name == (string)name) // 精确条件
                    .ExecuteCommand();
                //return "修改成功";
                var find_data_TC = Db.Queryable<daojiao_technology>()
                    .ToList();
                Console.WriteLine(find_data_TC.Count);
                return new
                {
                    data_all = find_data_TC,
                    type = "修改成功"
                };
            }
            else if((string)mes_data[0] == "删除")
            {
                var name = db_data["Name"];
                var rowsAffected = Db.Deleteable<daojiao_technology>()
                                .Where(it => it.Name == (string)name)
                                .ExecuteCommand();
                var find_data_TC = Db.Queryable<daojiao_technology>()
                    .ToList();
                return new
                {
                    data_all = find_data_TC,
                    type = "删除成功"
                };
            }
            else
            {
                Console.WriteLine("新增");
                var name = db_data["Name"];
                int count = Db.Queryable<daojiao_technology>()
                    .Where(it=>it.Name == (string)name)
                    .Count();
                if(count == 0)
                {
                    await Db.DoInsertAsync<daojiao_technology>(final_data_info);
                    var find_data_TC = Db.Queryable<daojiao_technology>()
                    .ToList();
                    return new
                    {
                        data_all = find_data_TC,
                        type = "新增成功"
                    };
                }
                else
                {
                    return new
                    {
                        data_all = "a",
                        type = "数据库已存在"
                    };
                }   

            }
            
        }

        public async Task<object> technology_db_lot_chaifen()
        {
            Console.WriteLine("查询");
            var find_data_TC = Db.Queryable<daojiao_technology>()
                .ToList();
            Console.WriteLine(find_data_TC.Count);
            return new
            {
                rows = find_data_TC,
                total = 1
            };
        }
        public async Task<object> get_db_djgdall()
        {
            Dictionary<string, string> statusDict = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "confirmed", "等待原材料" },
                    { "progress", "进行中" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                    { "produced", "产出" },
                    { "qc_pass", "质检完成" },
                    { "rework", "返工" },
                    { "done", "完成" },
                    { "to_close", "待关闭" },
                    { "cancel", "已取消" },
                };
            Dictionary<string, string> quality_state = new Dictionary<string, string>
                {
                    { "none", "待判定" },
                    { "major_pass", "通过主要检测" },
                    { "pass", "通过" },
                    { "givein", "通过1" },
                    { "recheck", "返检" },
                    { "rework", "返工" },
                    { "scrap", "报废" },
                    { "recycle", "再利用" },
                    { "downshift", "降档使用" }
                };
            
            Console.WriteLine("进来了！！！");
            var find_data = Db.Queryable<daojiaoGD>()
                    .ToList();


            Console.WriteLine(find_data);
            

            return find_data;
        }



        public async Task<object> get_db_quality_detailall()
        {
            Dictionary<string, string> statusDict = new Dictionary<string, string>
                {
                    { "draft", "新建" },
                    { "confirmed", "等待原材料" },
                    { "progress", "进行中" },
                    { "ready", "准备生产" },
                    { "in_production", "已开始生产" },
                    { "produced", "产出" },
                    { "qc_pass", "质检完成" },
                    { "rework", "返工" },
                    { "done", "完成" },
                    { "to_close", "待关闭" },
                    { "cancel", "已取消" },
                };
            Dictionary<string, string> quality_state = new Dictionary<string, string>
                {
                    { "none", "待判定" },
                    { "major_pass", "通过主要检测" },
                    { "pass", "通过" },
                    { "givein", "通过1" },
                    { "recheck", "返检" },
                    { "rework", "返工" },
                    { "scrap", "报废" },
                    { "recycle", "再利用" },
                    { "downshift", "降档使用" }
                };

            Console.WriteLine("进来了！！！");
            var find_data1 = Db.Queryable<daojiao_quality_info_table1>()
                .ToList();

            var find_data2 = Db.Queryable<daojiao_quality_info_table2>()
                    .ToList();
            var find_data3 = Db.Queryable<daojiao_quality_info_table3>()
                    .ToList();
            var resultDictionary = new Dictionary<string, object>
        {
            { "daojiao_quality_info_table1", find_data1 },
            { "daojiao_quality_info_table2", find_data2 },
            { "daojiao_quality_info_table3", find_data3 },
        };
            Console.WriteLine(find_data2);


            return resultDictionary;
        }

        [SugarTable("daojiao_quality_info_table1")] // 映射表名
        public class daojiao_quality_info_table1
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string order { get; set; }
            public string lot { get; set; }
            public string ProductName { get; set; }
            public string date_qian { get; set; }
            public string name_qian { get; set; }
            public string date_hou { get; set; }
            public string name_hou { get; set; }
            public int qty { get; set; }
            public string daojiao_ccxh1 { get; set; }
            public string daojiaoX { get; set; }
            public string daojiaoQ1 { get; set; }
            public string daojiaoQ2 { get; set; }
            public string daojiaoQ3 { get; set; }
            public string daojiaoQ4 { get; set; }
            public string daojiaoQ5 { get; set; }
            public string daojiaoQ6 { get; set; }
            public string daojiaoQ7 { get; set; }
            public string daojiaoQ8 { get; set; }
            public string daojiaoQ9 { get; set; }
            public string daojiaoQ10 { get; set; }
            public string daojiaoH1 { get; set; }
            public string daojiaoH2 { get; set; }
            public string daojiaoH3 { get; set; }
            public string daojiaoH4 { get; set; }
            public string daojiaoH5 { get; set; }
            public string daojiaoH6 { get; set; }
            public string daojiaoH7 { get; set; }
            public string daojiaoH8 { get; set; }
            public string daojiaoH9 { get; set; }
            public string daojiaoH10 { get; set; }
            public string R1 { get; set; }
            public string R2 { get; set; }
            public string R3 { get; set; }
            public string R4 { get; set; }
            public string R5 { get; set; }
            public string R6 { get; set; }
            public string R7 { get; set; }
            public string R8 { get; set; }
            public string R9 { get; set; }
            public string R10 { get; set; }
            public string wg1 { get; set; }
            public string wg2 { get; set; }
            public string wg3 { get; set; }
            public string wg4 { get; set; }
            public string wg5 { get; set; }
            public string wg6 { get; set; }
            public string wg7 { get; set; }
            public string wg8 { get; set; }
            public string wg9 { get; set; }
            public string wg10 { get; set; }
        }
        [SugarTable("daojiao_quality_info_table2")] // 映射表名
        public class daojiao_quality_info_table2
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string order { get; set; }
            public string lot { get; set; }
            public string ProductName { get; set; }
            public string date_qian { get; set; }
            public string name_qian { get; set; }
            public string date_hou { get; set; }
            public string name_hou { get; set; }
            public int qty { get; set; }
            public string daojiao_ccxh2 { get; set; }
            public string daojiaoX { get; set; }
            public string daojiaoQ1 { get; set; }
            public string daojiaoQ2 { get; set; }
            public string daojiaoQ3 { get; set; }
            public string daojiaoQ4 { get; set; }
            public string daojiaoQ5 { get; set; }
            public string daojiaoQ6 { get; set; }
            public string daojiaoH1 { get; set; }
            public string daojiaoH2 { get; set; }
            public string daojiaoH3 { get; set; }
            public string daojiaoH4 { get; set; }
            public string daojiaoH5 { get; set; }
            public string daojiaoH6 { get; set; }
            public string R1 { get; set; }
            public string R2 { get; set; }
            public string R3 { get; set; }
            public string R4 { get; set; }
            public string R5 { get; set; }
            public string R6 { get; set; }
            public string wg1 { get; set; }
            public string wg2 { get; set; }
            public string wg3 { get; set; }
            public string wg4 { get; set; }
            public string wg5 { get; set; }
            public string wg6 { get; set; }
        }
        [SugarTable("daojiao_quality_info_table3")] // 映射表名
        public class daojiao_quality_info_table3
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string order { get; set; }
            public string lot { get; set; }
            public string ProductName { get; set; }
            public string date_qian { get; set; }
            public string name_qian { get; set; }
            public string date_hou { get; set; }
            public string name_hou { get; set; }
            public int qty { get; set; }
            public string daojiao_ccxh3 { get; set; }
            public string daojiaoX { get; set; }
            public string daojiaoQ1 { get; set; }
            public string daojiaoQ2 { get; set; }
            public string daojiaoQ3 { get; set; }
            public string daojiaoQ4 { get; set; }
            public string daojiaoQ5 { get; set; }
            public string daojiaoQ6 { get; set; }
            public string daojiaoH1 { get; set; }
            public string daojiaoH2 { get; set; }
            public string daojiaoH3 { get; set; }
            public string daojiaoH4 { get; set; }
            public string daojiaoH5 { get; set; }
            public string daojiaoH6 { get; set; }
            public string R1 { get; set; }
            public string R2 { get; set; }
            public string R3 { get; set; }
            public string R4 { get; set; }
            public string R5 { get; set; }
            public string R6 { get; set; }
            public string wg1 { get; set; }
            public string wg2 { get; set; }
            public string wg3 { get; set; }
            public string wg4 { get; set; }
            public string wg5 { get; set; }
            public string wg6 { get; set; }
        }

        public async Task<object> insert_qul_info(JObject mes_data)
        {
            Console.WriteLine(mes_data["daojiao_quality_info_table1"]);
            Console.WriteLine(mes_data["daojiao_quality_info_table2"]);
            Console.WriteLine(mes_data["daojiao_quality_info_table3"]);
            JObject daojiao_quality_info_table1 = (JObject)mes_data["daojiao_quality_info_table1"];
            JObject daojiao_quality_info_table2 = (JObject)mes_data["daojiao_quality_info_table2"];
            JObject daojiao_quality_info_table3 = (JObject)mes_data["daojiao_quality_info_table3"];
            Console.WriteLine("????");
            Console.WriteLine((string)daojiao_quality_info_table1["daojiaoQ2"] != "" ? daojiao_quality_info_table1["daojiaoQ2"] : "DDD");
            Console.WriteLine("2222");
            var final_data_info1 = new List<daojiao_quality_info_table1>();
            var data_1 = new daojiao_quality_info_table1
            {
                order = (string)daojiao_quality_info_table1["order"],
                lot = (string)daojiao_quality_info_table1["lot"],
                ProductName = (string)daojiao_quality_info_table1["ProductName"],
                date_qian = (string)daojiao_quality_info_table1["date_qian"],
                name_qian = (string)daojiao_quality_info_table1["name_qian"],
                date_hou = (string)daojiao_quality_info_table1["date_hou"],
                name_hou = (string)daojiao_quality_info_table1["name_hou"],
                qty = (int)daojiao_quality_info_table1["qty"],
                daojiao_ccxh1 = (string)daojiao_quality_info_table1["daojiao_ccxh1"],
                daojiaoX = (string)daojiao_quality_info_table1["daojiaoX"],
                daojiaoQ1 = (string)daojiao_quality_info_table1["daojiaoQ1"],
                daojiaoQ2 = (string)daojiao_quality_info_table1["daojiaoQ2"],
                daojiaoQ3 = (string)daojiao_quality_info_table1["daojiaoQ3"],
                daojiaoQ4 = (string)daojiao_quality_info_table1["daojiaoQ4"],
                daojiaoQ5 = (string)daojiao_quality_info_table1["daojiaoQ5"],
                daojiaoQ6 = (string)daojiao_quality_info_table1["daojiaoQ6"],
                daojiaoQ7 = (string)daojiao_quality_info_table1["daojiaoQ7"],
                daojiaoQ8 = (string)daojiao_quality_info_table1["daojiaoQ8"],
                daojiaoQ9 = (string)daojiao_quality_info_table1["daojiaoQ9"],
                daojiaoQ10 = (string)daojiao_quality_info_table1["daojiaoQ10"],
                daojiaoH1 = (string)daojiao_quality_info_table1["daojiaoH1"],
                daojiaoH2 = (string)daojiao_quality_info_table1["daojiaoH2"],
                daojiaoH3 = (string)daojiao_quality_info_table1["daojiaoH3"],
                daojiaoH4 = (string)daojiao_quality_info_table1["daojiaoH4"],
                daojiaoH5 = (string)daojiao_quality_info_table1["daojiaoH5"],
                daojiaoH6 = (string)daojiao_quality_info_table1["daojiaoH6"],
                daojiaoH7 = (string)daojiao_quality_info_table1["daojiaoH7"],
                daojiaoH8 = (string)daojiao_quality_info_table1["daojiaoH8"],
                daojiaoH9 = (string)daojiao_quality_info_table1["daojiaoH9"],
                daojiaoH10 = (string)daojiao_quality_info_table1["daojiaoH10"],
                wg1 = (string)daojiao_quality_info_table1["wg1"],
                wg2 = (string)daojiao_quality_info_table1["wg2"],
                wg3 = (string)daojiao_quality_info_table1["wg3"],
                wg4 = (string)daojiao_quality_info_table1["wg4"],
                wg5 = (string)daojiao_quality_info_table1["wg5"],
                wg6 = (string)daojiao_quality_info_table1["wg6"],
                wg7 = (string)daojiao_quality_info_table1["wg7"],
                wg8 = (string)daojiao_quality_info_table1["wg8"],
                wg9 = (string)daojiao_quality_info_table1["wg9"],
                wg10 = (string)daojiao_quality_info_table1["wg10"],
                R1 = (string)daojiao_quality_info_table1["R1"],
                R2 = (string)daojiao_quality_info_table1["R2"],
                R3 = (string)daojiao_quality_info_table1["R3"],
                R4 = (string)daojiao_quality_info_table1["R4"],
                R5 = (string)daojiao_quality_info_table1["R5"],
                R6 = (string)daojiao_quality_info_table1["R6"],
                R7 = (string)daojiao_quality_info_table1["R7"],
                R8 = (string)daojiao_quality_info_table1["R8"],
                R9 = (string)daojiao_quality_info_table1["R9"],
                R10 = (string)daojiao_quality_info_table1["R10"],
            };
            final_data_info1.Add(data_1);

            var final_data_info2 = new List<daojiao_quality_info_table2>();
            var data_2 = new daojiao_quality_info_table2
            {
                order = (string)daojiao_quality_info_table2["order"],
                lot = (string)daojiao_quality_info_table2["lot"],
                ProductName = (string)daojiao_quality_info_table2["ProductName"],
                date_qian = (string)daojiao_quality_info_table2["date_qian"],
                name_qian = (string)daojiao_quality_info_table2["name_qian"],
                name_hou = (string)daojiao_quality_info_table2["name_hou"],
                qty = (int)daojiao_quality_info_table2["qty"],
                daojiao_ccxh2 = (string)daojiao_quality_info_table2["daojiao_ccxh2"],
                daojiaoX = (string)daojiao_quality_info_table2["daojiaoX"],
                daojiaoQ1 = (string)daojiao_quality_info_table2["daojiaoQ1"],
                daojiaoQ2 = (string)daojiao_quality_info_table2["daojiaoQ2"],
                daojiaoQ3 = (string)daojiao_quality_info_table2["daojiaoQ3"],
                daojiaoQ4 = (string)daojiao_quality_info_table2["daojiaoQ4"],
                daojiaoQ5 = (string)daojiao_quality_info_table2["daojiaoQ5"],
                daojiaoQ6 = (string)daojiao_quality_info_table2["daojiaoQ6"],
                daojiaoH1 = (string)daojiao_quality_info_table2["daojiaoH1"],
                daojiaoH2 = (string)daojiao_quality_info_table2["daojiaoH2"],
                daojiaoH3 = (string)daojiao_quality_info_table2["daojiaoH3"],
                daojiaoH4 = (string)daojiao_quality_info_table2["daojiaoH4"],
                daojiaoH6 = (string)daojiao_quality_info_table2["daojiaoH6"],
                wg1 = (string)daojiao_quality_info_table2["wg1"],
                wg2 = (string)daojiao_quality_info_table2["wg2"],
                wg3 = (string)daojiao_quality_info_table2["wg3"],
                wg4 = (string)daojiao_quality_info_table2["wg4"],
                wg5 = (string)daojiao_quality_info_table2["wg5"],
                wg6 = (string)daojiao_quality_info_table2["wg6"],
                R1 = (string)daojiao_quality_info_table2["R1"],
                R2 = (string)daojiao_quality_info_table2["R2"],
                R3 = (string)daojiao_quality_info_table2["R3"],
                R4 = (string)daojiao_quality_info_table2["R4"],
                R5 = (string)daojiao_quality_info_table2["R5"],
                R6 = (string)daojiao_quality_info_table2["R6"],
            };
            final_data_info2.Add(data_2);

            var final_data_info3 = new List<daojiao_quality_info_table3>();
            var data_3 = new daojiao_quality_info_table3
            {
                order = (string)daojiao_quality_info_table3["order"],
                lot = (string)daojiao_quality_info_table3["lot"],
                ProductName = (string)daojiao_quality_info_table3["ProductName"],
                date_qian = (string)daojiao_quality_info_table3["date_qian"],
                name_qian = (string)daojiao_quality_info_table3["name_qian"],
                date_hou = (string)daojiao_quality_info_table3["date_hou"],
                name_hou = (string)daojiao_quality_info_table3["name_hou"],
                qty = (int)daojiao_quality_info_table3["qty"],
                daojiao_ccxh3 = (string)daojiao_quality_info_table3["daojiao_ccxh3"],
                daojiaoX = (string)daojiao_quality_info_table3["daojiaoX"],
                daojiaoQ1 = (string)daojiao_quality_info_table3["daojiaoQ1"],
                daojiaoQ2 = (string)daojiao_quality_info_table3["daojiaoQ2"],
                daojiaoQ3 = (string)daojiao_quality_info_table3["daojiaoQ3"],
                daojiaoQ4 = (string)daojiao_quality_info_table3["daojiaoQ4"],
                daojiaoQ5 = (string)daojiao_quality_info_table3["daojiaoQ5"],
                daojiaoQ6 = (string)daojiao_quality_info_table3["daojiaoQ6"],
                daojiaoH1 = (string)daojiao_quality_info_table3["daojiaoH1"],
                daojiaoH2 = (string)daojiao_quality_info_table3["daojiaoH2"],
                daojiaoH3 = (string)daojiao_quality_info_table3["daojiaoH3"],
                daojiaoH4 = (string)daojiao_quality_info_table3["daojiaoH4"],
                daojiaoH5 = (string)daojiao_quality_info_table3["daojiaoH5"],
                daojiaoH6 = (string)daojiao_quality_info_table3["daojiaoH6"],
                wg1 = (string)daojiao_quality_info_table3["wg1"],
                wg2 = (string)daojiao_quality_info_table3["wg2"],
                wg3 = (string)daojiao_quality_info_table3["wg3"],
                wg4 = (string)daojiao_quality_info_table3["wg4"],
                wg5 = (string)daojiao_quality_info_table3["wg5"],
                wg6 = (string)daojiao_quality_info_table3["wg6"],
                R1 = (string)daojiao_quality_info_table3["R1"],
                R2 = (string)daojiao_quality_info_table3["R2"],
                R3 = (string)daojiao_quality_info_table3["R3"],
                R4 = (string)daojiao_quality_info_table3["R4"],
                R5 = (string)daojiao_quality_info_table3["R5"],
                R6 = (string)daojiao_quality_info_table3["R6"],
            };
            final_data_info3.Add(data_3);

            var name = daojiao_quality_info_table1["order"];
            int count1 = Db.Queryable<daojiao_quality_info_table1>()
                .Where(it => it.order == (string)name)
                .Count();

            if(count1 == 0)
            {
                await Db.DoInsertAsync<daojiao_quality_info_table1>(final_data_info1);
                await Db.DoInsertAsync<daojiao_quality_info_table2>(final_data_info2);
                await Db.DoInsertAsync<daojiao_quality_info_table3>(final_data_info3);
            }
            else
            {
                int rowsAffected1 = Db.Updateable<daojiao_quality_info_table1>()
                    .SetColumns(it => new daojiao_quality_info_table1
                    {
                        order = (string)daojiao_quality_info_table1["order"],
                        lot = (string)daojiao_quality_info_table1["lot"],
                        ProductName = (string)daojiao_quality_info_table1["ProductName"],
                        date_qian = (string)daojiao_quality_info_table1["date_qian"],
                        name_qian = (string)daojiao_quality_info_table1["name_qian"],
                        date_hou = (string)daojiao_quality_info_table1["date_hou"],
                        name_hou = (string)daojiao_quality_info_table1["name_hou"],
                        qty = (int)daojiao_quality_info_table1["qty"],
                        daojiao_ccxh1 = (string)daojiao_quality_info_table1["daojiao_ccxh1"],
                        daojiaoX = (string)daojiao_quality_info_table1["daojiaoX"],
                        daojiaoQ1 = (string)daojiao_quality_info_table1["daojiaoQ1"],
                        daojiaoQ2 = (string)daojiao_quality_info_table1["daojiaoQ2"],
                        daojiaoQ3 = (string)daojiao_quality_info_table1["daojiaoQ3"],
                        daojiaoQ4 = (string)daojiao_quality_info_table1["daojiaoQ4"],
                        daojiaoQ5 = (string)daojiao_quality_info_table1["daojiaoQ5"],
                        daojiaoQ6 = (string)daojiao_quality_info_table1["daojiaoQ6"],
                        daojiaoQ7 = (string)daojiao_quality_info_table1["daojiaoQ7"],
                        daojiaoQ8 = (string)daojiao_quality_info_table1["daojiaoQ8"],
                        daojiaoQ9 = (string)daojiao_quality_info_table1["daojiaoQ9"],
                        daojiaoQ10 = (string)daojiao_quality_info_table1["daojiaoQ10"],
                        daojiaoH1 = (string)daojiao_quality_info_table1["daojiaoH1"],
                        daojiaoH2 = (string)daojiao_quality_info_table1["daojiaoH2"],
                        daojiaoH3 = (string)daojiao_quality_info_table1["daojiaoH3"],
                        daojiaoH4 = (string)daojiao_quality_info_table1["daojiaoH4"],
                        daojiaoH5 = (string)daojiao_quality_info_table1["daojiaoH5"],
                        daojiaoH6 = (string)daojiao_quality_info_table1["daojiaoH6"],
                        daojiaoH7 = (string)daojiao_quality_info_table1["daojiaoH7"],
                        daojiaoH8 = (string)daojiao_quality_info_table1["daojiaoH8"],
                        daojiaoH9 = (string)daojiao_quality_info_table1["daojiaoH9"],
                        daojiaoH10 = (string)daojiao_quality_info_table1["daojiaoH10"],
                        wg1 = (string)daojiao_quality_info_table1["wg1"],
                        wg2 = (string)daojiao_quality_info_table1["wg2"],
                        wg3 = (string)daojiao_quality_info_table1["wg3"],
                        wg4 = (string)daojiao_quality_info_table1["wg4"],
                        wg5 = (string)daojiao_quality_info_table1["wg5"],
                        wg6 = (string)daojiao_quality_info_table1["wg6"],
                        wg7 = (string)daojiao_quality_info_table1["wg7"],
                        wg8 = (string)daojiao_quality_info_table1["wg8"],
                        wg9 = (string)daojiao_quality_info_table1["wg9"],
                        wg10 = (string)daojiao_quality_info_table1["wg10"],
                        R1 = (string)daojiao_quality_info_table1["R1"],
                        R2 = (string)daojiao_quality_info_table1["R2"],
                        R3 = (string)daojiao_quality_info_table1["R3"],
                        R4 = (string)daojiao_quality_info_table1["R4"],
                        R5 = (string)daojiao_quality_info_table1["R5"],
                        R6 = (string)daojiao_quality_info_table1["R6"],
                        R7 = (string)daojiao_quality_info_table1["R7"],
                        R8 = (string)daojiao_quality_info_table1["R8"],
                        R9 = (string)daojiao_quality_info_table1["R9"],
                        R10 = (string)daojiao_quality_info_table1["R10"],
                    })
                    .Where(it => it.order == (string)name) // 精确条件
                    .ExecuteCommand();
                int rowsAffected2 = Db.Updateable<daojiao_quality_info_table2>()
                    .SetColumns(it => new daojiao_quality_info_table2
                    {
                        order = (string)daojiao_quality_info_table2["order"],
                        lot = (string)daojiao_quality_info_table2["lot"],
                        ProductName = (string)daojiao_quality_info_table2["ProductName"],
                        date_qian = (string)daojiao_quality_info_table2["date_qian"],
                        name_qian = (string)daojiao_quality_info_table2["name_qian"],
                        name_hou = (string)daojiao_quality_info_table2["name_hou"],
                        qty = (int)daojiao_quality_info_table2["qty"],
                        daojiao_ccxh2 = (string)daojiao_quality_info_table2["daojiao_ccxh2"],
                        daojiaoX = (string)daojiao_quality_info_table2["daojiaoX"],
                        daojiaoQ1 = (string)daojiao_quality_info_table2["daojiaoQ1"],
                        daojiaoQ2 = (string)daojiao_quality_info_table2["daojiaoQ2"],
                        daojiaoQ3 = (string)daojiao_quality_info_table2["daojiaoQ3"],
                        daojiaoQ4 = (string)daojiao_quality_info_table2["daojiaoQ4"],
                        daojiaoQ5 = (string)daojiao_quality_info_table2["daojiaoQ5"],
                        daojiaoQ6 = (string)daojiao_quality_info_table2["daojiaoQ6"],
                        daojiaoH1 = (string)daojiao_quality_info_table2["daojiaoH1"],
                        daojiaoH2 = (string)daojiao_quality_info_table2["daojiaoH2"],
                        daojiaoH3 = (string)daojiao_quality_info_table2["daojiaoH3"],
                        daojiaoH4 = (string)daojiao_quality_info_table2["daojiaoH4"],
                        daojiaoH6 = (string)daojiao_quality_info_table2["daojiaoH6"],
                        wg1 = (string)daojiao_quality_info_table2["wg1"],
                        wg2 = (string)daojiao_quality_info_table2["wg2"],
                        wg3 = (string)daojiao_quality_info_table2["wg3"],
                        wg4 = (string)daojiao_quality_info_table2["wg4"],
                        wg5 = (string)daojiao_quality_info_table2["wg5"],
                        wg6 = (string)daojiao_quality_info_table2["wg6"],
                        R1 = (string)daojiao_quality_info_table2["R1"],
                        R2 = (string)daojiao_quality_info_table2["R2"],
                        R3 = (string)daojiao_quality_info_table2["R3"],
                        R4 = (string)daojiao_quality_info_table2["R4"],
                        R5 = (string)daojiao_quality_info_table2["R5"],
                        R6 = (string)daojiao_quality_info_table2["R6"],
                    })
                    .Where(it => it.order == (string)name) // 精确条件
                    .ExecuteCommand();
                int rowsAffected3 = Db.Updateable<daojiao_quality_info_table3>()
                    .SetColumns(it => new daojiao_quality_info_table3
                    {
                        order = (string)daojiao_quality_info_table3["order"],
                        lot = (string)daojiao_quality_info_table3["lot"],
                        ProductName = (string)daojiao_quality_info_table3["ProductName"],
                        date_qian = (string)daojiao_quality_info_table3["date_qian"],
                        name_qian = (string)daojiao_quality_info_table3["name_qian"],
                        date_hou = (string)daojiao_quality_info_table3["date_hou"],
                        name_hou = (string)daojiao_quality_info_table3["name_hou"],
                        qty = (int)daojiao_quality_info_table3["qty"],
                        daojiao_ccxh3 = (string)daojiao_quality_info_table3["daojiao_ccxh3"],
                        daojiaoX = (string)daojiao_quality_info_table3["daojiaoX"],
                        daojiaoQ1 = (string)daojiao_quality_info_table3["daojiaoQ1"],
                        daojiaoQ2 = (string)daojiao_quality_info_table3["daojiaoQ2"],
                        daojiaoQ3 = (string)daojiao_quality_info_table3["daojiaoQ3"],
                        daojiaoQ4 = (string)daojiao_quality_info_table3["daojiaoQ4"],
                        daojiaoQ5 = (string)daojiao_quality_info_table3["daojiaoQ5"],
                        daojiaoQ6 = (string)daojiao_quality_info_table3["daojiaoQ6"],
                        daojiaoH1 = (string)daojiao_quality_info_table3["daojiaoH1"],
                        daojiaoH2 = (string)daojiao_quality_info_table3["daojiaoH2"],
                        daojiaoH3 = (string)daojiao_quality_info_table3["daojiaoH3"],
                        daojiaoH4 = (string)daojiao_quality_info_table3["daojiaoH4"],
                        daojiaoH5 = (string)daojiao_quality_info_table3["daojiaoH5"],
                        daojiaoH6 = (string)daojiao_quality_info_table3["daojiaoH6"],
                        wg1 = (string)daojiao_quality_info_table3["wg1"],
                        wg2 = (string)daojiao_quality_info_table3["wg2"],
                        wg3 = (string)daojiao_quality_info_table3["wg3"],
                        wg4 = (string)daojiao_quality_info_table3["wg4"],
                        wg5 = (string)daojiao_quality_info_table3["wg5"],
                        wg6 = (string)daojiao_quality_info_table3["wg6"],
                        R1 = (string)daojiao_quality_info_table3["R1"],
                        R2 = (string)daojiao_quality_info_table3["R2"],
                        R3 = (string)daojiao_quality_info_table3["R3"],
                        R4 = (string)daojiao_quality_info_table3["R4"],
                        R5 = (string)daojiao_quality_info_table3["R5"],
                        R6 = (string)daojiao_quality_info_table3["R6"],
                    })
                    .Where(it => it.order == (string)name) // 精确条件
                    .ExecuteCommand();
            }
            return "";
  
            
        }
        // SQL转义方法：处理单引号等特殊字符（核心方法，解决"不存在EscapeSql"的错误）
        private string EscapeSql(string value)
        {
            if (string.IsNullOrEmpty(value))
                return string.Empty;
            // TDengine中字符串的单引号需要转义为两个单引号
            return value.Replace("'", "''");
        }

        [SugarTable("daojiao_shebei")] // 映射表名
        public class daojiao_shebei
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string name { get; set; }
            public string current_order { get; set; }
        }
        public async Task<object> insert_db_device_order(JObject mes_data)
        {
            //JObject daojiao_quality_info_table1 = (JObject)mes_data["daojiao_quality_info_table1"];
            var name = (string)mes_data["name"];
            var current_order = (string)mes_data["current_order"];
            int rowsAffected = Db.Updateable<daojiao_shebei>()
                    .SetColumns(it => new daojiao_shebei()
                    {
                        current_order = current_order,
                    })
                    .Where(it => it.name == name) // 精确条件
                    .ExecuteCommand();

            return "";
        }

        public async Task<object> get_per_little_lot_state_(string name)
        {
            //JObject daojiao_quality_info_table1 = (JObject)mes_data["daojiao_quality_info_table1"];
            //var name = (string)mes_data["name"];
            //var current_order = (string)mes_data["current_order"];
            var deviceState = new Dictionary<string, string>
            {
                {"0", "禁用"},
                {"10", "待上料"},
                {"11", "上磨料中"},
                {"12", "上工件中"},
                {"13", "上料完成"},
                {"20", "待研磨"},
                {"21", "研磨中"},
                {"22", "研磨完成"},
                {"30", "待下料"},
                {"31", "下料中"},
                {"32", "下料完成"}
            };
            var return_date_web = new List<object>();
            Console.WriteLine(name);

            var per_dev = new List<object>();
            var find_data3 = Db.Queryable<daojiaogd_gz>()
                    .Where(it => it.name == name)
                    .ToList();
            Console.WriteLine("222222222");
            Console.WriteLine(find_data3.Count);
            for (int i = 0; i < find_data3.Count; i++)
            {

                if (find_data3[i].device != null)                
                {
                    string devices = find_data3[i].device;
                    Console.WriteLine("???");
                    Console.WriteLine($"有设备: {find_data3[i].device}");
                    // 使用#分割字符串
                    string[] parts = devices.Split('#');
                    var current_state = "";
                    // 检查分割结果是否有效
                    if (parts.Length > 0 && int.TryParse(parts[0], out int num))
                    {
                        Console.WriteLine($"转换结果: {num}"); // 输出 3
                        if (num <= 10)
                        {
                            current_state = $"AT_1号线研磨机" + (num) + "状态";
                        }
                        else
                        {
                            current_state = "AT_2号线研磨机" + (num - 10) + "状态";
                        }
                        Console.WriteLine($"bianliang: {current_state}");
                        var connectionString = "protocol=WebSocket;host=10.16.12.72;port=6041;useSSL=false;username=root;password=taosdata";
                        // 1. 对变量进行SQL转义（防止单引号等特殊字符导致语法错误）
                        string escapedState = EscapeSql(current_state);
                        // 2. 拼接SQL语句（替换参数占位符）
                        string sql_State = $@"SELECT ts, log_value, identity 
                            FROM fastbee_log.device_D136Z1Q880A6 
                            WHERE identity = '{escapedState}' 
                               ORDER BY ts DESC LIMIT 1";
                        try
                        {
                            // 连接到 TDengine 服务器
                            var builder = new ConnectionStringBuilder(connectionString);
                            using (var client = TDengine.Driver.Client.DbDriver.Open(builder))
                            {
                                Console.WriteLine("成功连接到 TDengine 服务器");
                                using (var result = client.Query(sql_State))
                                {
                                    while (result.Read())
                                    {
                                        Console.WriteLine(result);
                                        var ts = (DateTime)result.GetValue(0);
                                        var value = Encoding.UTF8.GetString((byte[])result.GetValue(1));
                                        string name_db = Encoding.UTF8.GetString((byte[])result.GetValue(2));
                                        Console.WriteLine(name_db);
                                        string dev_sta = "";
                                        if (deviceState.TryGetValue("10", out string state))
                                        {
                                            Console.WriteLine(state); // 输出：待上料
                                            dev_sta = state;
                                        }
                                        per_dev.Add(
                                            new Dictionary<string, object>
                                                {
                                                {"ts",ts.ToString("yyyy-MM-dd HH:mm:ss") },
                                                {"value",dev_sta },
                                                {"name",name },
                                                {"div_name",find_data3[i].name },
                                                {"order",find_data3[i].little_lot }
                                                }
                                        );
                                        int rowsAffected = Db.Updateable<daojiaogd_gz>()
                                            .SetColumns(it => new daojiaogd_gz()
                                            {
                                                current_state = dev_sta,
                                            })
                                            .Where(it => it.little_lot == find_data3[i].little_lot) // 精确条件
                                            .ExecuteCommand();
                                    }
                                }
                                return_date_web.Add(per_dev);
                            }
                        }
                        catch (TDengineError e)
                        {
                            Console.WriteLine($"TDengine 错误: 代码={e.Code}, 消息={e.Error}");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"发生异常: {e.Message}");
                            Console.WriteLine(e.StackTrace);
                        }
                    }
                    else
                    {
                        Console.WriteLine("无法转换为整数");
                    }
                    
                }
            }
            

            return per_dev;
        }
        public async Task<object> get_real_db()
        {
            var find_data3 = Db.Queryable<daojiao_shebei_dj>()
                    .ToList();
            Console.WriteLine(find_data3[0].number);
            Console.WriteLine(find_data3.Count);
            var dataList = new List<object>();
            for (int i = 0; i < find_data3.Count; i++)
            {
                Console.WriteLine(find_data3[i].name);
                if (find_data3[i].name != "1#倒角机上下料") { 
                    int number = int.Parse(find_data3[i].number);
                    var current_state = "";
                    var current_time = "";
                    var current_feq = "";
                    if (i + 1 <= 10)
                    {
                        current_state = $"AT_1号线研磨机" + (i + 1) + "状态";
                        current_time = $"AT_1号线研磨机" + (i + 1) + "当前时间";
                        current_feq = $"AT_1号线研磨机" + (i + 1) + "当前频率";
                    }
                    else
                    {
                        current_state = "AT_2号线研磨机" + (i - 9) + "状态";
                        current_time = "AT_2号线研磨机" + (i - 9) + "当前时间";
                        current_feq = "AT_2号线研磨机" + (i - 9) + "当前频率";
                    }
                    var connectionString = "protocol=WebSocket;host=10.16.12.72;port=6041;useSSL=false;username=root;password=taosdata";
                    // 1. 对变量进行SQL转义（防止单引号等特殊字符导致语法错误）
                    string escapedState = EscapeSql(current_state);
                    string escapedTime = EscapeSql(current_time);
                    string escapedFeq = EscapeSql(current_feq);

                    // 2. 拼接SQL语句（替换参数占位符）
                    string sql_State = $@"SELECT ts, log_value, identity 
                            FROM fastbee_log.device_D136Z1Q880A6 
                            WHERE identity = '{escapedState}' 
                               ORDER BY ts DESC LIMIT 1";
                    string sql_Time = $@"SELECT ts, log_value, identity 
                            FROM fastbee_log.device_D136Z1Q880A6 
                            WHERE identity = '{escapedTime}' 
                               ORDER BY ts DESC LIMIT 1";
                    string sql_Feq = $@"SELECT ts, log_value, identity 
                            FROM fastbee_log.device_D136Z1Q880A6 
                            WHERE identity = '{escapedFeq}'
                                ORDER BY ts DESC LIMIT 1";
                    var sql_list = new List<string> { sql_State, sql_Time, sql_Feq };
                    //var sql = "SELECT * FROM fastbee_log.device_D136Z1Q880A6 LIMIT 1000";

                    try
                    {
                        // 连接到 TDengine 服务器
                        var builder = new ConnectionStringBuilder(connectionString);
                        using (var client = TDengine.Driver.Client.DbDriver.Open(builder))
                        {
                            Console.WriteLine("成功连接到 TDengine 服务器");
                            var per_dev = new List<object>();
                            for (int j = 0; j < sql_list.Count; j++)
                            {
                                using (var result = client.Query(sql_list[j]))
                                {
                                    while (result.Read())
                                    {
                                        Console.WriteLine(result);
                                        var ts = (DateTime)result.GetValue(0);
                                        var value = Encoding.UTF8.GetString((byte[])result.GetValue(1));
                                        string name = Encoding.UTF8.GetString((byte[])result.GetValue(2));
                                        Console.WriteLine(name);
                                        per_dev.Add(
                                            new Dictionary<string, object>
                                                {
                                                {"ts",ts.ToString("yyyy-MM-dd HH:mm:ss") },
                                                {"value",value },
                                                {"name",name },
                                                {"div_name",find_data3[i].name }
                                                }
                                        );
                                    }
                                }
                            }
                            dataList.Add(per_dev);
                            Console.WriteLine(dataList.ToString());
                        }
                    }
                    catch (TDengineError e)
                    {
                        Console.WriteLine($"TDengine 错误: 代码={e.Code}, 消息={e.Error}");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"发生异常: {e.Message}");
                        Console.WriteLine(e.StackTrace);
                    }
                }
            }
            return dataList;
        }

        public async Task<object> get_real_pro_db()
        {
            var find_data3 = Db.Queryable<daojiao_shebei_dj>()
                    .ToList();
            Console.WriteLine(find_data3[0].number);
            Console.WriteLine(find_data3.Count);
            var dataList = new List<object>();
            for (int i = 0; i < find_data3.Count; i++)
            {
                Console.WriteLine(find_data3[i].name);
                if (find_data3[i].name != "1#倒角机上下料")
                {
                    int number = int.Parse(find_data3[i].number);
                    var current_state = "";
                    var current_time = "";
                    var current_feq = "";
                    if (i + 1 <= 10)
                    {
                        current_state = $"AT_1号线" + (i + 1) + "号产品代码";
                        current_time = $"AT_1号线" + (i + 1) + "号规格";
                        current_feq = $"AT_1号线" + (i + 1) + "号性能";
                        current_feq = $"AT_1号线" + (i + 1) + "号批号";
                    }
                    else
                    {
                        current_state = $"AT_2号线" + (i + 1) + "号产品代码";
                        current_time = $"AT_2号线" + (i + 1) + "号规格";
                        current_feq = $"AT_2号线" + (i + 1) + "号性能";
                        current_feq = $"AT_2号线" + (i + 1) + "号批号";
                    }
                    var connectionString = "protocol=WebSocket;host=10.16.12.72;port=6041;useSSL=false;username=root;password=taosdata";
                    // 1. 对变量进行SQL转义（防止单引号等特殊字符导致语法错误）
                    string escapedState = EscapeSql(current_state);
                    string escapedTime = EscapeSql(current_time);
                    string escapedFeq = EscapeSql(current_feq);

                    // 2. 拼接SQL语句（替换参数占位符）
                    string sql_State = $@"SELECT ts, log_value, identity 
                            FROM fastbee_log.device_D136Z1Q880A6 
                            WHERE identity = '{escapedState}' 
                               ORDER BY ts DESC LIMIT 1";
                    string sql_Time = $@"SELECT ts, log_value, identity 
                            FROM fastbee_log.device_D136Z1Q880A6 
                            WHERE identity = '{escapedTime}' 
                               ORDER BY ts DESC LIMIT 1";
                    string sql_Feq = $@"SELECT ts, log_value, identity 
                            FROM fastbee_log.device_D136Z1Q880A6 
                            WHERE identity = '{escapedFeq}'
                                ORDER BY ts DESC LIMIT 1";
                    var sql_list = new List<string> { sql_State, sql_Time, sql_Feq };
                    //var sql = "SELECT * FROM fastbee_log.device_D136Z1Q880A6 LIMIT 1000";

                    try
                    {
                        // 连接到 TDengine 服务器
                        var builder = new ConnectionStringBuilder(connectionString);
                        using (var client = TDengine.Driver.Client.DbDriver.Open(builder))
                        {
                            Console.WriteLine("成功连接到 TDengine 服务器");
                            var per_dev = new List<object>();
                            for (int j = 0; j < sql_list.Count; j++)
                            {
                                using (var result = client.Query(sql_list[j]))
                                {
                                    while (result.Read())
                                    {
                                        Console.WriteLine(result);
                                        var ts = (DateTime)result.GetValue(0);
                                        var value = Encoding.UTF8.GetString((byte[])result.GetValue(1));
                                        string name = Encoding.UTF8.GetString((byte[])result.GetValue(2));
                                        Console.WriteLine(name);
                                        per_dev.Add(
                                            new Dictionary<string, object>
                                                {
                                                {"ts",ts.ToString("yyyy-MM-dd HH:mm:ss") },
                                                {"value",value },
                                                {"name",name },
                                                {"div_name",find_data3[i].name }
                                                }
                                        );
                                    }
                                }
                            }
                            dataList.Add(per_dev);
                            Console.WriteLine(dataList.ToString());
                        }
                    }
                    catch (TDengineError e)
                    {
                        Console.WriteLine($"TDengine 错误: 代码={e.Code}, 消息={e.Error}");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"发生异常: {e.Message}");
                        Console.WriteLine(e.StackTrace);
                    }
                }
            }
            return dataList;
        }

    }
    
}
